package com.diana.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class TokenUtils {

    private static final String key = "eghvesyu@#$%^anzhi&udx56fhv";
    private static Logger log = LoggerFactory.getLogger(TokenUtils.class);

    public static String getToken(String userId,int second){
        //key用来加密和分割
        //设置加密内容
        String content = Utils.MD5(userId)+key+(Utils.getSecondTimestamp(new Date())+second);
        String hexStr = Utils.AesEncrypt(content, key);
        return hexStr;
    }

    public static String getToken(String userId){
        //key用来加密和分割
        String content = Utils.MD5(userId)+key;
        String hexStr = Utils.AesEncrypt(content, key);
        return hexStr;
    }

    /**
     * 验证令牌
     * @param userId
     * @param token
     * @return
     */
    public static int vaildToken(String userId,String token){
        /*byte[] bytes = Utils.parseHexStr2Byte(token);
        byte[] result = Utils.AesDecrypt(bytes, key);*/
        //内容解码
        try {
            String strResult = Utils.AesDecrypt(token,key);
            String [] arr = strResult.replace(key,"##").split("##");
            if(arr.length!=2){
                return StatusEnums.CheckTokenStatus.令牌验证有误;
            }
            if(!Utils.MD5(userId).equals(arr[0])){
                return StatusEnums.CheckTokenStatus.令牌验证有误;
            }
            int tokenTime = Integer.parseInt(arr[1]);
            int now = Utils.getSecondTimestamp(new Date());
            if(tokenTime<now){
                return StatusEnums.CheckTokenStatus.令牌过期;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return StatusEnums.CheckTokenStatus.令牌验证有误;
        }
        return StatusEnums.CheckTokenStatus.验证通过;
    }
}
